const baseUrl = 'http://39.107.224.212:8081/api';

/**
 * 通用请求方法
 */
function request(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        'Authorization': wx.getStorageSync('token') || ''
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 处理后端返回的ResultVO格式
          if (res.data.code === 200) {
            resolve(res.data);
          } else {
            wx.showToast({
              title: res.data.message || '请求失败',
              icon: 'none'
            });
            reject(res.data);
          }
        } else {
          wx.showToast({
            title: res.data?.message || '请求失败',
            icon: 'none'
          });
          reject(res.data);
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        reject(err);
      }
    });
  });
}

// 商品相关API
function getProducts() {
  return request({
    url: '/products'
  });
}

function getProductsByCategory(categoryId) {
  return request({
    url: `/products/category/${categoryId}`
  });
}

function getProductById(id) {
  return request({
    url: `/products/${id}`
  });
}

// 订单相关API
function createOrder(orderData) {
  return request({
    url: '/orders/',
    method: 'POST',
    data: orderData
  });
}

function getOrdersByUser(userId) {
  return request({
    url: `/orders/user/${userId}`
  });
}

function getOrderByNo(orderNo) {
  return request({
    url: `/orders/${orderNo}`
  });
}

function getOrderDetail(orderNo) {
  return request({
    url: `/orders/${orderNo}/detail`
  });
}

function payOrder(orderNo) {
  return request({
    url: `/orders/${orderNo}/pay`,
    method: 'POST'
  });
}

function cancelOrder(orderNo) {
  return request({
    url: `/orders/${orderNo}/cancel`,
    method: 'POST'
  });
}

function getCategories() {
  return request({
    url: '/categories'
  });
}

module.exports = {
  getProducts,
  getProductsByCategory,
  getProductById,
  createOrder,
  getOrdersByUser,
  getOrderByNo,
  getOrderDetail,
  payOrder,
  cancelOrder,
  getCategories
};